<template>
  <!-- 系统管理 -->
  <div class="system-manage">

    <div class="app-container">
      <div class="mainbox">

        <Header header-name="系统管理" />

        <el-row :gutter="10" class="system-manage-body">

          <!-- 系统/项目树列表 -->
          <el-col :span="4" class="system-manage-left">
            <div v-loading="treeLoading">
              <el-input
                v-model="filterText"
                placeholder="项目/系统名称"
                clearable
              />

              <div class="add-group">
                <el-button v-permission="['SYSTEMMANAGE_ADD_SYSTEM']" type="primary" size="mini" @click="addSystemBtn"> 新增系统 </el-button>
                <el-button v-permission="['SYSTEMMANAGE_ADD_PROJECT']" size="mini" @click="addProjectBtn"> 新增项目 </el-button>
              </div>

              <el-tree
                ref="tree"
                :data="treeData"
                :props="defaultProps"
                default-expand-all
                node-key="id"
                :filter-node-method="filterNode"
                :highlight-current="true"
                :expand-on-click-node="false"
                @node-click="handleNodeClick"
              >
                <p slot-scope="{ node, data }" class="custom-tree-node">
                  <span :title="node.label" :class="[data.children.length === 0 && 'no-click']">{{ node.label }}</span>
                  <span class="tree-btn">
                    <el-button v-permission="['SYSTEMMANAGE_UPDATE']" type="text" icon="el-icon-edit-outline" @click="updateBtn(data, node)" />
                    <el-button v-permission="['SYSTEMMANAGE_DEL']" type="text" icon="el-icon-delete" class="text-del-btn" @click="delProjectBtn(data)" />
                  </span>
                </p>
              </el-tree>
            </div>
          </el-col>

          <el-col :span="20" class="system-manage-right">
            <div>
              <!-- 搜索项 -->
              <el-form ref="form" :model="form" inline label-width="80px" class="search-form">
                <el-form-item prop="systemName">
                  <el-input v-model="form.systemName" clearable :maxlength="50" placeholder="请输入系统名称或编号" />
                </el-form-item>

                <el-form-item prop="createUserId">
                  <el-select v-model="form.createUserId" clearable filterable placeholder="请选择创建人">
                    <el-option
                      v-for="(item, index) in createUserIdList"
                      :key="index"
                      :label="item.realName"
                      :value="item.userId"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item prop="headUserId">
                  <el-select v-model="form.headUserId" clearable filterable placeholder="请选择负责人/分配用户">
                    <el-option
                      v-for="(item, index) in createUserIdList"
                      :key="index"
                      :label="item.realName"
                      :value="item.userId"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item class="query-action">
                  <el-button type="primary" :loading="loading" :disabled="loading" @click="searchBtn"> 查询 </el-button>
                  <el-button :loading="loading" :disabled="loading" @click="resetBtn"> 重置 </el-button>
                  <!-- <el-button type="danger" :disabled="!multipleSelection.length" @click="delProjectBtn('batch')"> 删除 </el-button> -->
                </el-form-item>
              </el-form>

              <!-- 表格 -->
              <FlexTable
                v-loading="loading"
                border
                :data="tableData"
                :columns="columnsOptions"
                @selection-change="handleSelectionChange"
              />

              <el-pagination
                :page-size="pagination.pageSize"
                :current-page.sync="pagination.pageNo"
                layout="prev, pager, next, jumper"
                :total="pagination.totalPage"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-col>
        </el-row>

        <!-- 新增/编辑项目 -->
        <el-dialog
          title="新增/编辑项目"
          :visible.sync="projectDialogVisible"
          :close-on-click-modal="false"
          width="600px"
        >
          <el-form ref="projectForm" :rules="projectFormRules" :model="projectForm" label-width="100px">
            <el-form-item label="项目名称:" prop="systemName">
              <el-input v-model.trim="projectForm.systemName" clearable :maxlength="50" placeholder="请输入项目名称" />
            </el-form-item>

            <el-form-item v-if="updateId" label="项目编码:">
              {{ projectForm.systemCode }}
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="projectDialogVisible = false">取 消</el-button>
            <el-button type="primary" :loading="!canClick" :disabled="!canClick" @click="addSystemInfoBtn('projectForm')">确 定</el-button>
          </span>
        </el-dialog>

        <!-- 新增/编辑系统 -->
        <el-dialog
          title="新增/编辑系统"
          :visible.sync="systemDialogVisible"
          :close-on-click-modal="false"
          width="650px"
        >
          <el-form ref="systemForm" :rules="systemFormRules" :model="systemForm" label-width="150px">
            <el-form-item label="所属项目:" prop="projectId">
              <el-select
                v-model="systemForm.projectId"
                :disabled="!!updateId"
                clearable
                placeholder="请选择项目"
                @change="getPidList"
              >
                <el-option
                  v-for="(item, index) in projectList"
                  :key="index"
                  :label="item.systemName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="上级系统:" prop="pid">
              <el-cascader
                v-model="systemForm.pid"
                :placeholder="systemForm.projectId ? '请选择上级系统' : '请先选择所属项目'"
                :disabled="!!updateId"
                clearable
                :options="pidList"
                :props="{ checkStrictly: true, value: 'id', label: 'systemName' }"
              />
            </el-form-item>

            <el-form-item label="系统名称:" prop="systemName">
              <el-input v-model="systemForm.systemName" :maxlength="50" clearable placeholder="请输入系统名称" />
            </el-form-item>

            <el-form-item v-if="updateId" label="系统编码:">
              {{ systemForm.systemCode }}
            </el-form-item>

            <el-form-item label="负责人姓名/手机号:" prop="headUserId">
              <el-select
                v-model="systemForm.headUserId"
                filterable
                clearable
                placeholder="请选择负责人"
              >
                <el-option
                  v-for="(item, index) in createUserIdList"
                  :key="index"
                  :label="item.realName + ' / ' + item.phone"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="systemDialogVisible = false">取 消</el-button>
            <el-button type="primary" :loading="!canClick" :disabled="!canClick" @click="addSystemInfoBtn('systemForm')">确 定</el-button>
          </span>
        </el-dialog>

        <!-- 分配用户弹框 -->
        <assigned-user ref="assignedUser" :system-id="updateId" :head-user-id="headUserId" :create-user-id-list="createUserIdList" />
      </div>
    </div>
  </div>
</template>

<script>
import AssignedUser from './components/AssignedUser'
import { getSystemInfoTreeApi, getSystemInfoPageApi,
  addSystemInfoApi, getSystemUserBySystemInfoApi,
  deleteSystemInfoApi } from '@/api/systemManage'
import sysUserApi from '@/framework/api/userCenter/sysUser'
import _ from 'lodash' // 导入loadsh插件
export default {
  name: 'SystemManage',

  components: {
    AssignedUser
  },

  data () {
    return {
      // 负责人
      headUserId: '',
      // 是否可以点击确定按钮，避免多次提交
      canClick: true,
      filterText: '',
      form: {
        systemName: '',
        createUserId: '',
        headUserId: ''
      },
      defaultProps: {
        children: 'children',
        label: 'systemName'
      },
      treeLoading: false,
      treeData: [],

      createrOptions: [],
      loading: false,
      tableData: [],
      columnsOptions: [
        // { type: 'selection' },
        { label: '系统名称', prop: 'systemName' },
        { label: '系统编号', prop: 'systemCode' },
        { label: '创建时间', prop: 'createTime' },
        { label: '创建人', prop: 'createUserName' },
        { label: '负责人', prop: 'headUserName' },
        { label: '负责人手机号码', prop: 'headUserPhone' },
        { label: '操作', width: 200,
          customRender: (scope) => {
            return [
              <el-button vPermission={['SYSTEMMANAGE_UPDATE']} type='text' onClick={() => this.updateBtn(scope.row, { level: 2 })}> 修改 </el-button>,
              <el-button vPermission={['SYSTEMMANAGE_ASSIGNEDUSER']} type='text' onClick={() => this.assignedUserBtn(scope.row)}> 分配用户 </el-button>,
              <el-button vPermission={['SYSTEMMANAGE_DEL']} type='text' class='text-del-btn' onClick={() => this.delProjectBtn(scope.row)}> 删除 </el-button>
            ]
          }
        }
      ],

      projectDialogVisible: false,
      // 项目列表
      projectList: [],
      projectForm: {
        systemName: ''
      },
      projectFormRules: {
        systemName: { required: true, message: '请输入项目名称', trigger: 'blur' }
      },
      systemDialogVisible: false,
      // 上级系统列表
      pidList: [],
      // 负责人列表
      headUserIdList: [],
      createUserIdList: [],
      systemForm: {
        projectId: '',
        pid: [],
        systemName: '',
        headUserId: ''
      },
      systemFormRules: {
        projectId: { required: true, message: '请选择项目', trigger: 'change' },
        pid: { required: true, message: '请选择上级系统', trigger: ['blur', 'change'] },
        systemName: { required: true, message: '请输入系统名称', trigger: ['blur'] },
        headUserId: { required: true, message: '请选择负责人', trigger: ['change'] }
      },
      // 选中的表格
      multipleSelection: [],
      // 分页相关
      pagination: {
        pageNo: 1,
        pageSize: 10,
        totalPage: 0
      },

      // 点击左侧树列表获取到的id
      pid: '',
      // 要修改的数据id
      updateId: '',
      // 要修改的数据pid
      updatePId: ''
    }
  },

  watch: {
    filterText (val) {
      this.$refs.tree.filter(val)
    }
  },

  created () {
    this.getSystemInfoTree()
    sysUserApi.fetchPage({
      organizationId: this.$store.getters.orgId,
      pageNo: 1,
      pageSize: -1,
      containSelf: true
    }).then(({ code, data }) => {
      if (code === '00000') {
        this.createUserIdList = data.rows
      }
    })
    this.getSystemInfoPage()
  },

  methods: {
    filterNode (value, data) {
      if (!value) return true
      return data.systemName.indexOf(value) !== -1
    },

    // 搜索按钮
    searchBtn () {
      this.getSystemInfoPage()
    },

    // 重置按钮
    resetBtn () {
      this.$refs.form.resetFields()
      this.getSystemInfoPage()
    },

    // 点击树列表
    handleNodeClick (data) {
      this.$refs.tree.setCurrentKey()
      if (data.children.length === 0) {
        if (this.pid) this.$refs.tree.setCurrentKey(this.pid)
        return
      }
      this.pid = data.id
      this.$refs.tree.setCurrentKey(this.pid)
      this.$refs.form.resetFields()
      this.getSystemInfoPage()
    },

    // 多选表格
    handleSelectionChange (val) {
      this.multipleSelection = val
    },

    // 获取表格数据
    getSystemInfoPage() {
      this.loading = true
      getSystemInfoPageApi({
        pageNo: this.pagination.pageNo,
        pageSize: this.pagination.pageSize,
        systemType: 1,
        pid: this.pid,
        ...this.form
      }).then(({ code, data }) => {
        if (code === '00000') {
          this.tableData = data.rows
          this.pagination.totalPage = data.totalRows
        }
      }).finally(() => {
        this.loading = false
      })
    },

    // 获取左侧树列表
    getSystemInfoTree () {
      this.treeLoading = true
      getSystemInfoTreeApi()
        .then(({ code, data }) => {
          if (code === '00000') {
            this.treeData = data
          }
        }).finally(() => {
          this.treeLoading = false
        })
    },

    // 新增项目按钮
    async addProjectBtn () {
      this.updateId = undefined
      this.projectDialogVisible = true
      this.projectForm = {
        systemName: ''
      }
      await this.$nextTick()
      this.$refs.projectForm.clearValidate()
    },

    // 新增系统按钮
    async addSystemBtn () {
      this.updateId = undefined
      this.systemDialogVisible = true
      this.getSystemBasicData()
      this.systemForm = {
        projectId: '',
        pid: [],
        systemName: '',
        headUserId: ''
      }
      await this.$nextTick()
      this.$refs.systemForm.clearValidate()
    },

    getSystemBasicData () {
      this.projectList = this.treeData.map((item) => {
        return {
          id: item.id,
          systemName: item.systemName
        }
      })

      // if (this.headUserIdList.length > 0) return
      // this.getHeadUserIdList()
    },

    // 获取负责人列表
    getHeadUserIdList () {
      sysUserApi.fetchPage({
        organizationId: this.$store.getters.orgId,
        pageNo: 1,
        pageSize: -1,
        containSelf: false
      }).then(({ code, data }) => {
        if (code === '00000') {
          this.headUserIdList = data.rows
        }
      })
    },

    // 项目/系统确定按钮
    addSystemInfoBtn (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {}
          if (formName === 'projectForm') {
            params = {
              id: this.updateId,
              systemName: this.projectForm.systemName,
              // 0:项目 1:系统
              systemType: 0
            }
          } else {
            const systemFormParams = _.cloneDeep(this.systemForm)
            params = {
              id: this.updateId,
              systemName: systemFormParams.systemName,
              pid: systemFormParams.pid.at([-1]),
              pids: systemFormParams.pid.join(','),
              headUserId: systemFormParams.headUserId,
              // 0:项目 1:系统
              systemType: 1
            }
          }

          this.canClick = false
          addSystemInfoApi(
            params,
            this.updateId
          )
            .then(({ code }) => {
              if (code === '00000') {
                this.projectDialogVisible = false
                this.systemDialogVisible = false
                this.getSystemInfoTree()
                // if (this.pid === this.updatePId) {
                this.getSystemInfoPage()
                // }
              }
            }).finally(() => {
              this.canClick = true
            })
        }
      })
    },

    // 删除项目/系统按钮
    delProjectBtn (data) {
      this.$confirm('此操作将永久删除该节点下所有数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSystemInfoApi({
          id: data.id
        }).then(({ code }) => {
          if (code === '00000') {
            this.$message.success('删除成功')
            if (this.pid === data.pid) {
              this.getSystemInfoPage()
              this.pid = ''
              this.$refs.form.resetFields()
            }
            this.getSystemInfoTree()
          }
        })
      })
    },

    // 修改按钮
    async updateBtn (data, node) {
      this.updateId = data.id
      this.updatePId = data.pid
      if (node.level === 1) {
        // 项目弹框
        this.projectDialogVisible = true
        this.projectForm.systemName = data.systemName
        this.projectForm.systemCode = data.systemCode
        await this.$nextTick()
        this.$refs.projectForm.clearValidate()
      } else {
        // 系统弹框
        this.systemDialogVisible = true
        this.systemForm.systemName = data.systemName
        this.systemForm.pid = data.pids.split(',')
        this.systemForm.projectId = data.pids.split(',')[0]
        this.systemForm.headUserId = data.headUserId
        this.systemForm.systemCode = data.systemCode
        this.getSystemBasicData()
        this.getPidList(this.systemForm.projectId, true)
      }
    },

    // 所属项目切换，获取上级系统
    getPidList (value, other) {
      if (!other) this.systemForm.pid = ''

      // 递归操作，若children为[]，则删除children，不展示后边的展开箭头
      const children = _.cloneDeep(this.treeData.filter(item => item.id === value)[0].children)
      const handleChild = (arr) => {
        arr.forEach(item => {
          if (item.children && item.children.length !== 0) {
            handleChild(item.children)
          } else {
            delete item.children
          }
        })
      }

      handleChild(children)
      this.pidList = this.systemForm.projectId ? [
        {
          id: value,
          systemName: '/',
          children: children
        }
      ] : []
    },

    // 分配用户按钮
    assignedUserBtn(row) {
      this.$refs.assignedUser.dialogVisible = true
      this.$refs.assignedUser.getCreateUserIdListInPage()
      this.updateId = row.id
      this.headUserId = row.headUserId
      getSystemUserBySystemInfoApi({
        systemId: row.id
      }).then(({ code, data }) => {
        if (code === '00000') {
          this.$refs.assignedUser.checkListInPage = [...data, this.headUserId]
        }
      })
    },

    // 分页操作
    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.getSystemInfoPage()
    },
    handleCurrentChange (val) {
      this.pagination.pageNo = val
      this.getSystemInfoPage()
    }
  }
}
</script>

<style lang="scss" scoped>
  .system-manage {
    background: #F2F2F2;

    .system-manage-body {
      margin-top: 10px;
      height: calc(100vh - 254px);
      > .el-col {
        height: 100%;
        > div {
          height: 100%;
          padding: 10px;
          background-color: #fff;
        }
      }

      // 系统/项目树列表
      .system-manage-left {
        width: 300px;
        .add-group {
          text-align: right;
          padding: 10px 0;
        }

        .el-tree {
          height: calc(100% - 100px);
          overflow-y: auto;
          ::v-deep .el-tree-node__expand-icon {
            font-size: 18px;
          }
          .custom-tree-node {
            width: calc(100% - 30px);
            padding-right: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;

            > span:first-child {
              display: inline-block;
              width: calc(100% - 50px);
              overflow: hidden;
              white-space: nowrap;
              text-overflow: ellipsis;
              line-height: 40px;
            }
            ::v-deep .tree-btn i {
              font-size: 18px;
            }
          }

          .no-click {
            cursor: default;
          }
        }
      }

      .system-manage-right {
        width: calc(100% - 300px);
        > div {
          overflow-y: auto;
        }
      }
    }

    .el-pagination {
      text-align: right;
      margin-top: 20px;
    }

    ::v-deep .el-dialog {
      .el-input, .el-select {
        width: 400px;
      }
    }
  }
</style>
